<?php
session_start();
include_once("auth_process.php");
?>
<?php
function handleError($e)
{
    error_log("category_detail.php, Error: " . $e->getMessage());
    echo "Sorry, some errors happened. Please try later !";
    exit();
}

include_once("db_connection.php");

try {
    $conn = getdb();
    $stmt = $conn->prepare("SELECT catid , cname  FROM categories");
    $stmt->execute();

    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
    $categories = $stmt->fetchAll();
} catch (Exception $e) {
    handleError($e);
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link href="../css/common.css" rel="stylesheet" type="text/css"/>
    <link href="../css/nav_list.css" rel="stylesheet" type="text/css"/>
    <style>
        body {
            min-width: 800px;
        }

        p {
            font-size: 24px;
        }

        #current_category_items {
            margin-right: 90px;
            margin-top: 30px;
            border: 3px solid gainsboro;
            overflow: auto;
            padding-bottom: 60px;
            min-height: 530px;
            clear: right;
        }

        .goods_item {
            border: 2px solid white;
            display: inline-block;
            vertical-align: top;
            margin: 8px;
            padding-bottom: 10px;
            height: 360px;
            width: 350px;

        }

        .item_pic {
            display: block;
            margin: auto;
            width: 200px;
            height: 200px;
        }

        .item_name {
            text-align: center;
            max-width: 360px;
            padding-left: 10px;
            padding-right: 10px;
        }

        .item_name a:link {
            color: black;
            text-decoration: none;
        }

        .item_name a:hover {
            color: black;
            text-decoration: underline;
        }

        .item_name a:visited {
            color: black;
            text-decoration: none;
        }

        .item_price {
            text-align: center;
        }

        ul.pagination {
            display: inline-block;
            padding: 0;
            margin-top: 5px;
            width: 100%;
            margin-left: 46%;
        }

        ul.pagination li {
            display: inline;
        }

        ul.pagination li a {
            color: black;
            float: left;
            padding: 8px 16px;
            text-decoration: none;
            border-radius: 5px;
        }

        ul.pagination li a.active {
            background-color: #4CAF50;
            color: white;
            border-radius: 5px;
        }

        ul.pagination li a:hover:not(.active) {
            background-color: #ddd;
        }

    </style>
    <title>Freewheel Shopping Online</title>
</head>
<body>
<?php
$username = getCurrentUsername();
if ($username['result'] != true) {
    echo "<p  id='login_entry'><a href='login.php'>Hi, please login!</a></p>";
} else {
    echo "<p  id='login_entry'>Hello, " . htmlspecialchars($username['username']) . " | <a href='logout.php'>Log out</a></p>";
}
$cart_token = md5(time() . "cart_token" . rand(0, 9999));
$_SESSION['cart_token'] = $cart_token;
?>
<div id="container">
    <?php readfile("../htmls/header.html") ?>
    <div id="body">
        <nav id="category_list">
            <ul>
                <?php

                foreach ($categories as $k => $v) {
                    if ($v['catid'] == $_GET['catid']) {
                        $current_category = $v;
                    }
                    echo "<li><a href=\"category_detail.php?catid=" . $v['catid'] . "\">" . htmlspecialchars($v['cname']) . "</a></li>\n";
                }

                ?>

            </ul>
        </nav>

        <nav id="nav_menu">
            <a href="index.php">Home</a> &gt;
            <?php
            if ($current_category != null) {
                echo "<a href=\"category_detail.php?catid=" . $current_category['catid'] . "\">" . htmlspecialchars($current_category['cname']) . "</a>\n";
            }
            ?>
        </nav>

        <?php include_once("shopping_cart_form.php") ?>

        <section id="current_category_items">
            <?php
            if ($current_category != null) {

//   --- handle pagination
                $pagesize = 4;

                try {
                    $stmt = $conn->prepare("SELECT COUNT(*) FROM products WHERE catid = :catid");
                    $stmt->bindParam(':catid', $_GET['catid']);
                    $stmt->execute();

                    $stmt->setFetchMode(PDO::FETCH_NUM);
                    $row = $stmt->fetch();
                    $product_nums = $row[0];
                } catch (Exception $e) {
                    handleError($e);
                }

                $total_pages = intval($product_nums / $pagesize);
                if ($product_nums % $pagesize) {
                    $total_pages++;
                }
                if (isset($_GET['page'])) {
                    $current_page = intval($_GET['page']);
                    $current_page = ($current_page <= 0) ? 1 : $current_page;
                    $current_page = ($current_page > $total_pages) ? $total_pages : $current_page;
                } else {
                    $current_page = 1;
                }
                $offset = $pagesize * ($current_page - 1);

                try {
                    $stmt = $conn->prepare("SELECT pid  ,pname  , price, description,extension  FROM products WHERE catid = :catid  LIMIT {$offset},{$pagesize}");
                    $stmt->bindParam(':catid', $_GET['catid']);
                    $stmt->execute();

                    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
                    $products = $stmt->fetchAll();
                } catch (Exception $e) {
                    handleError($e);
                }

                foreach ($products as $k => $v) {
                    echo "  <div class=\"goods_item\">
                        <a href=\"product_detail.php?pid=" . $v['pid'] . "\">
                            <img src = '../images/re_products/product" . $v['pid'] . "." . htmlspecialchars($v['extension']) . "' alt=\"" . htmlspecialchars($v['pname']) . "\" class=\"item_pic\">
                        </a>
                        <p class=\"item_name\"><a href=\"product_detail.php?pid=" . $v['pid'] . "\">" . htmlspecialchars($v['pname']) . "</a></p>
                        <p class=\"item_price\"><span> HK$ " . htmlspecialchars($v['price']) . "</span>  <input type=\"button\" id=\"btn{$v['pid']}\" value=\"Add To Cart\" class=\"add_to_cart\"/></p>
                    </div>";
                }

            } else {
                echo "<script>window.location.href = \"./index.php\"</script>";
            }
            $conn = null;
            ?>

        </section>
        <ul class="pagination">
            <?php
            if ($current_page == 1) {
                echo "<li><a href=\"#\">«</a></li>";
            } else {
                $prev_page = $current_page - 1;
                echo "<li><a href=\"./category_detail.php?catid={$_GET['catid']}&page={$prev_page}\">«</a></li>";
            }

            for ($i = 1; $i <= $total_pages; $i++) {
                if ($i == $current_page) {
                    echo "<li><a class=\"active\" href=\"#\">{$i}</a></li>";
                } else {
                    echo "<li><a href=\"./category_detail.php?catid={$_GET['catid']}&page={$i}\">{$i}</a></li>";
                }
            }
            if ($current_page == $total_pages) {
                echo "<li><a href=\"#\">»</a></li>";
            } else {
                $next_page = $current_page + 1;
                echo "<li><a href=\"./category_detail.php?catid={$_GET['catid']}&page={$next_page}\">»</a></li>";
            }

            ?>

        </ul>
    </div>
    <?php readfile("../htmls/footer.html") ?>
</div>
<script type="text/javascript" src="../javascripts/myLib.js"></script>
<script type="text/javascript" src="../javascripts/shopping_cart.js"></script>
<script>
    <?php
    foreach ($products as $k => $v) {
        echo "document.querySelector(\"#btn{$v['pid']}\").onclick = addToCart({$v['pid']});";
    }
    ?>

</script>

</body>
</html>

